package vip.george.p0021;


public class P21 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode resultHead = new ListNode();
        ListNode resultPoint = resultHead;
        ListNode l1 = list1;
        ListNode l2 = list2;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                resultPoint.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                resultPoint.next = l2;
                l2 = l2.next;
            }
            resultPoint = resultPoint.next;
        }
        if (l1 != null) {
            while (l1 != null) {
                resultPoint.next = new ListNode(l1.val);
                l1 = l1.next;
                resultPoint = resultPoint.next;
            }
        }
        if (l2 != null) {
            while (l2 != null) {
                resultPoint.next = new ListNode(l2.val);
                l2 = l2.next;
                resultPoint = resultPoint.next;
            }
        }
        return resultHead.next;
    }

    public static void main(String[] args) {
        P21 p21 = new P21();
        ListNode list11 =  p21.new ListNode(1);
        ListNode list12 =  p21.new ListNode(2);
        ListNode list13 =  p21.new ListNode(4);
        list11.next = list12;
        list12.next = list13;
        ListNode list21 =  p21.new ListNode(1);
        ListNode list22 =  p21.new ListNode(3);
        ListNode list23 =  p21.new ListNode(4);
        list21.next = list22;
        list22.next = list23;
        ListNode result = p21.mergeTwoLists(list11, list21);
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
        System.out.println();

    }
}
